<template>
  <q-dialog
    v-model="visible"
    seamless
    :position="$q.screen.lt.sm ? 'top' : 'left'"
  >
    <q-card style="max-height: calc(100vh - 2rem); width: 17.1rem">
      <q-card-section class="row items-center no-wrap">
        <div>
          <div class="text-subtitle1 text-bold">编辑点位连线</div>
          <div class="text-grey-7">{{ point.name }}</div>
        </div>
        <q-space />
        <q-btn flat round icon="close" v-close-popup />
      </q-card-section>
      <q-separator />
      <q-card-section v-if="online">
        <div v-if="mapOptions.length !== 0">
          <q-select
            outlined
            style="min-width: 10rem"
            v-model="selectedMap"
            :options="mapOptions"
            behavior="menu"
            label="选择组内地图"
          />
          <q-separator class="q-mt-sm q-mb-sm" />
        </div>
        <q-list
          bordered
          separator
          dense
          style="overflow: auto; max-height: 40vh"
        >
          <q-item v-for="(item, index) in poseOptions" :key="index">
            <q-item-section>{{ item.name }}</q-item-section>
            <q-item-section side>
              <q-toggle
                color="teal-6"
                v-model="connectList"
                :val="item.id"
                @click="toggle(item.id)"
              />
            </q-item-section>
          </q-item>
        </q-list>
      </q-card-section>
      <q-separator />
      <q-input
        label="当前占用机器人"
        outlined
        class="q-mr-sm q-ml-sm q-mt-sm"
        readonly
        v-if="!local && occupies[point.id]"
        :model-value="occupies[point.id]"
      />
      <q-card-section class="row q-gutter-sm q-pa-sm">
        <q-btn
          label="清除连线"
          color="warning"
          icon-right="clear"
          @click="clear"
        />
        <template v-if="!local">
          <q-btn
            v-if="![null, ''].includes(point.group)"
            label="释放该组"
            icon="delete"
            color="secondary"
            @click="releaseGroup"
          />
          <q-btn
            v-else
            label="释放占用"
            color="primary"
            icon="delete"
            @click="release"
          />
          <q-btn
            label="下发指令"
            color="primary"
            icon-right="send"
            @click="moveCmdDialog.show()"
            outline
          />
        </template>
        <q-btn
          :disable="!online"
          color="secondary"
          outline
          icon="edit"
          label="更多修改"
          @click="modifyMapPose.show(mapPose)"
        />
      </q-card-section>
    </q-card>
  </q-dialog>
  <move-cmd-dialog ref="moveCmdDialog" :pose="point" />
  <modify-map-pose ref="modifyMapPose" modify @update="getMapPoses" />
</template>

<script>
import { ref, inject, watch, computed } from "vue";
import { api } from "boot/axios";
import { useAPIStore } from "stores/api";
import { useQuasar } from "quasar";

import MoveCmdDialog from "components/rosMapRemote/pose/MoveCmdDialog.vue";
import ModifyMapPose from "components/rosMapRemote/pose/ModifyMapPose.vue";

export default {
  name: "EditRoute",
  props: {
    local: { type: Boolean, default: false },
  },
  components: {
    ModifyMapPose,
    MoveCmdDialog,
  },
  setup(props) {
    const $q = useQuasar();
    const online = inject("online");
    // 当前地图
    const mapId = inject("mapId");
    // 当前地图所在的地图组实体列表
    const mapGroupList = props.local ? [] : inject("mapGroupList");
    // 画线
    const drawRoutes = inject("drawRoutes");
    // 点位列表
    const pointList = inject("pointList");
    // 选中的点
    const point = ref({});
    const mapPose = ref({});
    const pointIndex = ref(0); // 角标
    // 连接点列表
    const connectList = ref([]);
    // 地图组内列表
    const mapOptions = ref([]);
    // 当前地图组内列表所选中的
    const selectedMap = ref({ label: "当前地图" });
    // 点位选项
    const poseOptions = ref([]);

    watch(selectedMap, () => {
      if (!online.value) return;
      api
        .get(useAPIStore().mapUrl + "mapPose/mapID/" + selectedMap.value.value)
        .then((res) => {
          poseOptions.value = res.data;
        });
    });

    const visible = ref(false);
    const show = function (index) {
      // 获取点信息
      point.value = pointList.value[index];
      api
        .get(useAPIStore().mapUrl + "mapPose/id/" + point.value.id)
        .then((rs) => {
          if (!online.value) return;
          mapPose.value = rs.data;
        });
      pointIndex.value = index;
      // 获取点信息中的connectPose信息
      connectList.value = point.value.connectedPose || [];

      if (!props.local) {
        // 生成组内地图列表
        mapOptions.value =
          mapGroupList.value.length === 0
            ? []
            : mapGroupList.value
                .map((v) => {
                  return { value: v.id, label: v.name };
                })
                .concat({ value: mapId.value, label: "当前地图" });
        // 选中当前地图
        selectedMap.value.value = mapId.value;
      }
      poseOptions.value = pointList.value;
      visible.value = true;
    };

    // 修改连线，重新规划
    watch(connectList, (value) => {
      pointList.value[pointIndex.value].connectedPose = value;
      drawRoutes(pointList.value);
    });

    return {
      occupies: props.local ? [] : inject("occupies"),
      visible,
      online,
      point,
      mapPose,
      poseOptions: computed(() =>
        poseOptions.value.filter((item) => point.value.id !== item.id)
      ),
      show,
      connectList,
      selectedMap,
      mapOptions,
      moveCmdDialog: ref(),
      modifyMapPose: ref(),
      toggle(poseID) {
        pointList.value.forEach((data) => {
          if (data.id === poseID) {
            if (connectList.value.indexOf(poseID) === -1) {
              data.connectedPose.splice(
                data.connectedPose.indexOf(point.value.id),
                1
              );
            } else {
              data.connectedPose.push(point.value.id);
            }
          }
        });
      },
      clear() {
        pointList.value.forEach((data) => {
          if (connectList.value.includes(data.id)) {
            data.connectedPose.splice(
              data.connectedPose.indexOf(point.value.id),
              1
            );
          }
        });
        connectList.value = [];
      },
      release() {
        $q.dialog({
          title: "释放占用点",
          message: "是否要释放" + point.value.name + "？",
          ok: "确认",
          cancel: "取消",
        }).onOk(() => {
          api
            .get(useAPIStore().centerUrl + "navigation/release", {
              params: { poseID: point.value.id },
            })
            .then((rs) => {
              if (rs.data === "done")
                $q.notify({ type: "positive", message: "点位释放成功" });
            });
        });
      },
      releaseGroup() {
        $q.dialog({
          title: "释放组",
          message: "是否要释放" + point.value.group + "组？",
          ok: "确认",
          cancel: "取消",
        }).onOk(() => {
          api
            .get(useAPIStore().centerUrl + "navigation/release/group", {
              params: { group: point.value.group },
            })
            .then((rs) => {
              if (rs.data === "done")
                $q.notify({ type: "positive", message: "分组占用已清除" });
            });
        });
      },
      getMapPoses() {
        api
          .get(useAPIStore().mapUrl + "mapPose/id/" + point.value.id)
          .then((rs) => {
            if (!online.value) return;
            console.log(rs);
            mapPose.value = rs.data;
          });
      },
    };
  },
};
</script>
